package com.xiaolun.join;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {
	//10以内进行拆分（计算临界）
	private static final Integer ADJUST_VALUE = 10;
	private int begin; //开始 0
	private int end; //结束 100
	private int result;

	public MyTask(int begin, int end) {
		this.begin = begin;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		if ((end - begin) <= ADJUST_VALUE) {
			for (int i = begin; i <= end; i++) {
				result = result + i;
			}
		} else {
			int middle = (begin + end) / 2;
			MyTask task01 = new MyTask(begin, middle);
			MyTask task02 = new MyTask(middle + 1, end);
			task01.fork();  //回来调用compute方法
			task02.fork();
			result = task01.join() + task02.join();
		}
		return result;
	}
}

/**
 * 分支合并例子
 * ForkJoinPool
 * ForkJoinTask
 * RecursiveTask
 */
public class ForkJoinDemo {
	public static void main(String[] args) throws ExecutionException, InterruptedException {
		MyTask myTask = new MyTask(0, 100); //任务
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
		System.out.println(forkJoinTask.get());
		forkJoinPool.shutdown();
	}
}
